//
//  ZKBombView.m
//  Private_Object
//
//  Created by pro on 16/9/7.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ZKBombView.h"

@implementation ZKBombView
{
    
    // picker subviews and property begin
    UIPickerView        *   _picker;                // 选择器
    UIDatePicker        *   _datePicker;            // 时间选择器
    
    UIButton            *   _leftButton;            // 左侧按钮（取消）
    UIButton            *   _rightButton;           // 右侧按钮（确定）
    UILabel             *   _titleLabel;            // 标题label
    UILabel             *   _sepLine;               // 分割线

    NSInteger               _selectedRow;           // 当前选中的行
    NSDateComponents    *   _selectComponents;      // 当前选中的时间组合
    // picker subviews and property end
    
    // date picker
}
#pragma mark - init
- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupDefault];
    }
    return self;
}

- (void)setupDefault {
    
    // 设置自身的属性
    self.bounds = [UIScreen mainScreen].bounds;
    
    // 背景半透明视图
    _maskView = [UIButton buttonWithType:UIButtonTypeCustom];
    _maskView.frame = self.bounds;
    _maskView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    _maskView.alpha = 0.0;
    [self addSubview:_maskView];
    [_maskView addTarget:self action:@selector(remove) forControlEvents:UIControlEventTouchUpInside];
}


#pragma mark - layout UI
- (void)setupUI {
    _contentView.x = SCREEN_WIDTH / 2;

    switch (self.positionMode) {
        case ZKBombPositionModeBottom:
            _contentView.top = SCREEN_HEIGHT;
            break;
        case ZKBombPositionModeCenter:
        {
            switch (self.popMode) {
                case ZKBombPopModeBottom:
                    _contentView.top = SCREEN_HEIGHT;
                    break;
                case ZKBombPopModeCenter:
                    _contentView.y = SCREEN_HEIGHT / 2;
                    break;
                case ZKBombPopModeTop:
                    _contentView.bottom = 0;
                    break;
                default:
                    break;
            }
        }
            break;
        case ZKBombPositionModeTop:
            _contentView.bottom = 0;
            break;
        default:
            break;
    }
}

#pragma mark - getter
- (CGFloat)aniDuration {
    if (_aniDuration == 0.0) {
        _aniDuration = 0.5;
    }
    return _aniDuration;
}
- (CGFloat)damping {
    if (_damping == 0.0) {
        _damping = 1.0;
    }
    return _damping;
}
- (UIFont *)font {
    if (!_font) {
        _font = [UIFont systemFontOfSize:17];
    }
    return _font;
}
- (UIColor *)titleColor {
    if (!_titleColor) {
        _titleColor = [UIColor darkGrayColor];
    }
    return _titleColor;
}
- (UIColor *)itemColor {
    if (!_itemColor) {
        _itemColor = [UIColor darkGrayColor];
    }
    return _itemColor;
}
- (CGFloat)pickerHeight {
    if (_pickerHeight == 0.0) {
        _pickerHeight = 240.0;
    }
    return _pickerHeight;
}

#pragma mark - setter
- (void)setContentMode:(ZKBombContentMode)contentMode {
    _contentMode = contentMode;
    if (_contentMode == ZKBombContentModePicker) {      // picker
        // 创建picker
        [self createPicker];
        return;
    }
    if (_contentMode == ZKBombContentModeDatePicker) {
        [self createDatePicker];
        return;
    }
    
}
- (void)setPositionMode:(ZKBombPositionMode)positionMode {
    _positionMode = positionMode;
    [self setupUI];
}
- (void)setPopMode:(ZKBombPopMode)popMode {
    _popMode = popMode;
    [self setupUI];
}
- (void)setUsePickerTitleForCustomContentMode:(BOOL)usePickerTitleForCustomContentMode {
    _usePickerTitleForCustomContentMode = usePickerTitleForCustomContentMode;
    if (self.contentView) {
        NSLog(@"请在设置contentView之前设置属性");
    }
}
- (void)setContentView:(UIView *)contentView {
    if (self.usePickerTitleForCustomContentMode) {
        // 创建内容视图
        UIView *realContentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
        realContentView.backgroundColor = [UIColor whiteColor];
        _contentView = realContentView;
        // 创建titleview
        [self createPickerTitleView];
        // 设置高度
        _contentView.height = _sepLine.bottom + contentView.height;
        // 添加我们自定义的视图
        [_contentView addSubview:contentView];
        // 调整我们自定义的视图的位置
        contentView.top = _sepLine.bottom;
    } else {
        _contentView = contentView;
    }
    
    [self addSubview:_contentView];
    [self setupUI];
}
- (void)setTitle:(NSString *)title {
    if (self.contentMode == ZKBombContentModePicker ||
        self.contentMode == ZKBombContentModeDatePicker) {
        _title = title;
        _titleLabel.text = _title;
    } else {
        NSLog(@"请先设置contentMode为picker");
    }
}

#pragma mark - picker
// 创建视图
- (void)createPicker {
    CGFloat x = 0;
    CGFloat y = SCREEN_HEIGHT;
    CGFloat width = SCREEN_WIDTH;
    CGFloat height = self.pickerHeight;
    // 创建内容视图
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    contentView.backgroundColor = [UIColor whiteColor];
    [self setContentView:contentView];
    
    // 创建picker的titleview
    [self createPickerTitleView];
    
    // 创建picker
    x = 0;
    y = _sepLine.bottom;
    width = self.contentView.width;
    height = self.contentView.height - y;
    _picker = [[UIPickerView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    _picker.backgroundColor = [UIColor whiteColor];
    _picker.delegate = self;
    _picker.dataSource = self;
    [contentView addSubview:_picker];
    [self clearSpearatorLine];
}

- (void)clearSpearatorLine
{
    [_picker.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (obj.frame.size.height < 1)
        {
            [obj setBackgroundColor:[UIColor clearColor]];
        }
    }];
}


// 创建picker 的titleview
- (void)createPickerTitleView {
    
    CGFloat x = 0;
    CGFloat y = SCREEN_HEIGHT;
    CGFloat width = SCREEN_WIDTH;
    CGFloat height = self.pickerHeight;
    // 创建顶部的左右按钮 和 中间的标题
    width = 44;
    height = 35;
    x = 15;
    y = 0;
    UIButton *leftButton = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [leftButton setTitle:@"取消" forState:UIControlStateNormal];
    [leftButton setTitleColor:self.titleColor forState:UIControlStateNormal];
    [leftButton.titleLabel setFont:self.font];
    [leftButton addTarget:self action:@selector(cancelTap) forControlEvents:UIControlEventTouchUpInside];
//    [self.contentView addSubview:_leftButton = leftButton];
    
    
    width = 44;
    height = 35;
    x = self.contentView.width - 15 - width;
    y = 0;
    UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [rightButton setTitle:@"完成" forState:UIControlStateNormal];
    [rightButton setTitleColor:self.titleColor forState:UIControlStateNormal];
    [rightButton.titleLabel setFont:self.font];
    [rightButton addTarget:self action:@selector(okTap) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_rightButton = rightButton];
    
    x = leftButton.right;
    y = 0;
    width = rightButton.left - x;
    height = rightButton.height;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    titleLabel.font = self.font;
    titleLabel.text = @"";
    titleLabel.textColor = self.titleColor;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:_titleLabel = titleLabel];
    
    // 创建分割线
    x = 0;
    y = titleLabel.bottom;
    width = self.contentView.width;
    height = 0.5;
    UILabel *sepLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    sepLabel.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
    [self.contentView addSubview:_sepLine = sepLabel];
}
// picker delegate
#pragma mark - picker delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.dataItems.count;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 44;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return self.contentView.width;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    _selectedRow = row;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view {
    UILabel *label = [[UILabel alloc] init];
    label.text = self.dataItems[row];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = self.itemColor;
    label.font = FONT(16);
    return label;
}

#pragma mark - date picker
- (void)createDatePicker {
    CGFloat x = 0;
    CGFloat y = SCREEN_HEIGHT;
    CGFloat width = SCREEN_WIDTH;
    CGFloat height = self.pickerHeight;
    // 创建内容视图
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    contentView.backgroundColor = [UIColor whiteColor];
    [self setContentView:contentView];
    
    // 创建picker的titleview
    [self createPickerTitleView];
    
    // 创建picker
    x = 0;
    y = _sepLine.bottom;
    width = self.contentView.width;
    height = self.contentView.height - y;
    _datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(x, y, width, height)];
    _datePicker.backgroundColor = [UIColor whiteColor];
    [_datePicker setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
    [_datePicker setTimeZone:[NSTimeZone localTimeZone]];
    _datePicker.datePickerMode = UIDatePickerModeDate;
    [_datePicker addTarget:self action:@selector(dataPickerDidChangeValue:) forControlEvents:UIControlEventValueChanged];
    [contentView addSubview:_datePicker];
    if (!self.minDate) {
        self.minDate = [NSDate date];
    }
    _datePicker.minimumDate = self.minDate;
    _datePicker.maximumDate = self.maxDate;
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    _selectComponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:self.minDate];
}
// 时间改变了
- (void)dataPickerDidChangeValue:(UIDatePicker *)picker {
    NSCalendar *calendar = picker.calendar;
    _selectComponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:picker.date];
}
#pragma mark - tap
- (void)disableTapMask {
    
    _maskView.userInteractionEnabled = NO;
    
}
- (void)show {
    
    // 把本视图添加到窗口上
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [self setCenter:[UIApplication sharedApplication].keyWindow.center];
    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self];
    
    // 显示动画
    [self contentViewShowAnimation];
}
- (void)remove {
    
    // 隐藏动画
    [self contentViewRemoveAnimation];
}
- (void)cancelTap {
    [self remove];
}
- (void)okTap {
    if (self.pickerDidSelected) {
        self.pickerDidSelected(self.dataItems[_selectedRow]);
    } else if (self.datePickerDidSelected) {
        self.datePickerDidSelected(_selectComponents);
    } else if (self.customTapOk) {
        self.customTapOk();
    }
    
    [self remove];
}



#pragma mark - animation
- (void)contentViewShowAnimation {
    
    if (self.popMode == ZKBombPopModeCenter && self.positionMode == ZKBombPositionModeCenter) {
        self.contentView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.01, 0.01);
        _maskView.alpha = 0;
    }
    [UIView animateWithDuration:self.aniDuration delay:0 usingSpringWithDamping:self.damping initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        
        _maskView.alpha = 1;

        switch (self.positionMode) {
            case ZKBombPositionModeBottom:       // 从下方弹出
                self.contentView.bottom = SCREEN_HEIGHT;
                break;
            case ZKBombPositionModeCenter:       // 从下方弹出
            {
                switch (self.popMode) {
                    case ZKBombPopModeCenter:
                        self.contentView.transform = CGAffineTransformIdentity;
                        break;
                    default:
                        self.contentView.y = SCREEN_HEIGHT / 2;
                        break;
                }
            }
                break;
            case ZKBombPositionModeTop:          // 从上方落下
                self.contentView.top = 0;
                break;
                
            default:
                break;
        }
    } completion:^(BOOL finished) {
    }];
}
- (void)contentViewRemoveAnimation {
    
    if (self.popMode == ZKBombPopModeCenter && self.positionMode == ZKBombPositionModeCenter) {
        _maskView.alpha = 1;
    }
    
    [UIView animateWithDuration:self.aniDuration delay:0 usingSpringWithDamping:self.damping initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseOut animations:^{

        _maskView.alpha = 0;
        
        switch (self.positionMode) {
            case ZKBombPositionModeBottom:       // 从下方弹出
                self.contentView.top = SCREEN_HEIGHT;
                break;
            case ZKBombPositionModeCenter:       // 从下方弹出
            {
                switch (self.popMode) {
                    case ZKBombPopModeCenter:
                        self.contentView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.01, 0.01);
                        break;
                    default:
                        self.contentView.top = SCREEN_HEIGHT;
                        break;
                }
            }
                break;
            case ZKBombPositionModeTop:          // 从上方落下
                self.contentView.bottom = 0;
                break;
                
            default:
                break;
        }
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

@end
